package com.fowo.api.syncAmazon.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.amazon.spapi.api.ReportsApi;
import com.amazon.spapi.model.reports.CreateReportSpecification;
import com.amazon.spapi.model.reports.Report;
import com.amazon.spapi.model.reports.ReportDocument;
import com.amazon.spapi.model.reports.ReportOptions;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fowo.api.datainterface.entity.DatainterfaceAuthority;
import com.fowo.api.datainterface.service.DatainterfaceAuthorityService;
import com.fowo.api.entity.*;
import com.fowo.api.mapper.ListingFatherMapper;
import com.fowo.api.service.impl.ShopInfoServiceImpl;
import com.fowo.api.service.impl.TmpBusinessReportsByChildServiceImpl;
import com.fowo.api.service.impl.TmpBusinessReportsByParentServiceImpl;
import com.fowo.api.service.impl.TmpBusinessReportsBySkuServiceImpl;
import com.fowo.api.syncAmazon.util.AmazonUtil;
import com.fowo.api.syncAmazon.util.AmzDateUtils;
import com.fowo.api.syncAmazon.util.GeneralUtil;
import com.squareup.okhttp.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.util.*;
import java.util.zip.GZIPInputStream;

@Component
@Slf4j
public class BusinessReportsService extends ReportService {

    @Resource
    private DatainterfaceAuthorityService datainterfaceAuthorityBaseService;
    @Resource
    private AmazonUtil amazonUtil;
    @Resource
    private ShopInfoServiceImpl shopInfoService;
    @Resource
    private TmpBusinessReportsBySkuServiceImpl tmpBusinessReportsBySkuService;
    @Resource
    private TmpBusinessReportsByChildServiceImpl tmpBusinessReportsByChildService;
    @Resource
    private TmpBusinessReportsByParentServiceImpl tmpBusinessReportsByParentService;

    /**
     * 商品业务报表 数据
     * @throws Exception
     */
    public void getBusinessReportsBySku() throws Exception {
        DatainterfaceAuthority entityAuthority = datainterfaceAuthorityBaseService.getOne(Wrappers.<DatainterfaceAuthority>lambdaQuery().eq(DatainterfaceAuthority::getAppCode,"Amazon"), false);

        final List<ShopInfo> list = shopInfoService.list(Wrappers.lambdaQuery(ShopInfo.class)
                .eq(ShopInfo::getPlatform,"Amazon")
                .eq(ShopInfo::getSellerAuthStatus,"SQ01"));
        for(ShopInfo shop : list){

            List<String> marketplaceIds = Arrays.asList(shop.getMarketplaceId().split(","));

            CreateReportSpecification body = new CreateReportSpecification();
            body.setReportType("GET_SALES_AND_TRAFFIC_REPORT");
            body.setMarketplaceIds(marketplaceIds);
            ReportOptions reportOptions = new ReportOptions();
            reportOptions.put("dateGranularity","MONTH");
            reportOptions.put("asinGranularity","SKU");

            body.setReportOptions(reportOptions);

            body.setDataStartTime(AmzDateUtils.getOffsetDateTimeUTC(DateUtil.offsetMonth(new Date(),-6)));
            body.setDataEndTime(AmzDateUtils.getOffsetDateTimeUTC(DateUtil.offsetMonth(new Date(),-6)));

            // 第一步 创建报告
            ReportsApi reportsApi = amazonUtil.getReportsApi(entityAuthority,shop,0.0167);
            final String reportId = createReport(reportsApi, body);
            // 第二步 检验报告是否完成
            ReportsApi reportsApi2 = amazonUtil.getReportsApi(entityAuthority,shop,2.0);
            final Report report = getReport(reportsApi2, reportId);
            // 第三步 获取报告连接
            ReportsApi reportsApi3 = amazonUtil.getReportsApi(entityAuthority,shop,0.0167);
            final ReportDocument reportDocument = reportsApi3.getReportDocument(report.getReportDocumentId());
            // 第四步 下载报告
            String compressionAlgorithm = null;
            if(null != reportDocument.getCompressionAlgorithm()){
                compressionAlgorithm = reportDocument.getCompressionAlgorithm().getValue();
            }
            System.out.println(reportDocument.getUrl());
            download(reportDocument.getUrl(),compressionAlgorithm,shop);

        }
    }

    @Override
    public void download(String url, String compressionAlgorithm, ShopInfo shop) throws IOException, IllegalArgumentException {
        OkHttpClient httpclient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

        Response response = httpclient.newCall(request).execute();
        if (!response.isSuccessful()) {
            System.out.println(
                    String.format("Call to download content was unsuccessful with response code: %d and message: %s",
                            response.code(), response.message()));
            return;
        }

        try (ResponseBody responseBody = response.body()) {
            MediaType mediaType = MediaType.parse(response.header("Content-Type"));
            Charset charset = mediaType.charset();
            if (charset == null) {
                throw new IllegalArgumentException(String.format(
                        "Could not parse character set from '%s'", mediaType.toString()));
            }

            Closeable closeThis = null;
            try {
                InputStream inputStream = responseBody.byteStream();
                closeThis = inputStream;

                if ("GZIP".equals(compressionAlgorithm)) {
                    inputStream = new GZIPInputStream(inputStream);
                    closeThis = inputStream;
                }

                // This example assumes that the download content has a charset in the content-type header, e.g.
                // text/plain; charset=UTF-8
                if ("text".equals(mediaType.type()) && "plain".equals(mediaType.subtype())) {
                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream, charset);
                    closeThis = inputStreamReader;

                    BufferedReader reader = new BufferedReader(inputStreamReader);
                    closeThis = reader;

                    String line;
                    List<TmpBusinessReportsBySku> list = new ArrayList<>();
                    CopyOptions copyOptions = CopyOptions.create();
                    copyOptions.setOverride(false);
                    copyOptions.setIgnoreNullValue(true);
                    while ((line = reader.readLine()) != null) {
                        JSONObject json = GeneralUtil.getJsonObject(line);
                        JSONArray salesAndTrafficByAsin = json.getJSONArray("salesAndTrafficByAsin");
                        JSONObject reportSpecification = json.getJSONObject("reportSpecification");
                        Date dataTime = reportSpecification.getDate("dataStartTime");
//                        JSONArray marketplaceIds = reportSpecification.getJSONArray("marketplaceIds");
//                        String marketplaceid = marketplaceIds.getString(0);
                        for(int i = 0 ; i < salesAndTrafficByAsin.size() ; i++) {
                            TmpBusinessReportsBySku tmp = new TmpBusinessReportsBySku();
                            JSONObject itemJson = salesAndTrafficByAsin.getJSONObject(i);
                            String parentAsin = itemJson.getString("parentAsin");
                            String childAsin = itemJson.getString("childAsin");
                            String sku = itemJson.getString("sku");
                            JSONObject salesByAsin = itemJson.getJSONObject("salesByAsin");
                            JSONObject trafficByAsin = itemJson.getJSONObject("trafficByAsin");

                            Integer unitsOrdered = salesByAsin.getInteger("unitsOrdered");
                            Integer unitsOrderedB2B = salesByAsin.getInteger("unitsOrderedB2B");
                            Integer totalOrderItems = salesByAsin.getInteger("totalOrderItems");
                            Integer totalOrderItemsB2B = salesByAsin.getInteger("totalOrderItemsB2B");
                            JSONObject orderedProductSalesJson = salesByAsin.getJSONObject("orderedProductSales");
                            BigDecimal orderedProductSales = orderedProductSalesJson.getBigDecimal("amount");
                            String currency = orderedProductSalesJson.getString("currencyCode");
                            JSONObject orderedProductSalesB2BJson = salesByAsin.getJSONObject("orderedProductSalesB2B");
                            BigDecimal orderedProductSalesB2B = new BigDecimal("0");
                            if(orderedProductSalesB2BJson != null) {
                                orderedProductSalesB2B = orderedProductSalesB2BJson.getBigDecimal("amount");
                            }

                            TmpBusinessReportsBySku trafficByAsinBean = JSONObject.toJavaObject(trafficByAsin, TmpBusinessReportsBySku.class);
//                            Integer browserSessions = trafficByAsin.getInteger("browserSessions");
//                            Integer browserSessionsB2B = trafficByAsin.getInteger("browserSessionsB2B");
//                            Integer mobileAppSessions = trafficByAsin.getInteger("mobileAppSessions");
//                            Integer mobileAppSessionsB2B = trafficByAsin.getInteger("mobileAppSessionsB2B");
//                            Integer sessions = trafficByAsin.getInteger("sessions");
//                            Integer sessionsB2B = trafficByAsin.getInteger("sessionsB2B");
//                            BigDecimal browserSessionPercentage = trafficByAsin.getBigDecimal("browserSessionPercentage");
//                            BigDecimal browserSessionPercentageB2B = trafficByAsin.getBigDecimal("browserSessionPercentageB2B");
//                            BigDecimal mobileAppSessionPercentage = trafficByAsin.getBigDecimal("mobileAppSessionPercentage");
//                            BigDecimal mobileAppSessionPercentageB2B = trafficByAsin.getBigDecimal("mobileAppSessionPercentageB2B");
//                            BigDecimal sessionPercentage = trafficByAsin.getBigDecimal("sessionPercentage");
//                            BigDecimal sessionPercentageB2B = trafficByAsin.getBigDecimal("sessionPercentageB2B");
//                            Integer browserPageViews = trafficByAsin.getInteger("browserPageViews");
//                            Integer browserPageViewsB2B = trafficByAsin.getInteger("browserPageViewsB2B");
//                            Integer mobileAppPageViews = trafficByAsin.getInteger("mobileAppPageViews");
//                            Integer mobileAppPageViewsB2B = trafficByAsin.getInteger("mobileAppPageViewsB2B");
//                            Integer pageViews = trafficByAsin.getInteger("pageViews");
//                            Integer pageViewsB2B = trafficByAsin.getInteger("pageViewsB2B");
//                            BigDecimal browserPageViewsPercentage = trafficByAsin.getBigDecimal("browserPageViewsPercentage");
//                            BigDecimal browserPageViewsPercentageB2B = trafficByAsin.getBigDecimal("browserPageViewsPercentageB2B");
//                            BigDecimal mobileAppPageViewsPercentage = trafficByAsin.getBigDecimal("mobileAppPageViewsPercentage");
//                            BigDecimal mobileAppPageViewsPercentageB2B = trafficByAsin.getBigDecimal("mobileAppPageViewsPercentageB2B");
//                            BigDecimal pageViewsPercentage = trafficByAsin.getBigDecimal("pageViewsPercentage");
//                            BigDecimal pageViewsPercentageB2B = trafficByAsin.getBigDecimal("pageViewsPercentageB2B");
//                            BigDecimal buyBoxPercentage = trafficByAsin.getBigDecimal("buyBoxPercentage");
//                            BigDecimal buyBoxPercentageB2B = trafficByAsin.getBigDecimal("buyBoxPercentageB2B");
//                            BigDecimal unitSessionPercentage = trafficByAsin.getBigDecimal("unitSessionPercentage");
//                            BigDecimal unitSessionPercentageB2B = trafficByAsin.getBigDecimal("unitSessionPercentageB2B");
                            tmp.setCreateTime(new Date());
                            tmp.setLastUpdateTime(new Date());
                            tmp.setSid(shop.getId());
                            tmp.setCurrency(currency);
                            tmp.setMsku(sku);
                            tmp.setChildAsin(childAsin);
                            tmp.setParentAsin(parentAsin);
                            tmp.setDataTime(dataTime);
                            tmp.setUnitsOrdered(unitsOrdered);
                            tmp.setUnitsOrderedB2b(unitsOrderedB2B);
                            tmp.setTotalOrderItems(totalOrderItems);
                            tmp.setTotalOrderItemsB2b(totalOrderItemsB2B);
                            tmp.setOrderedProductSales(orderedProductSales);
                            tmp.setOrderedProductSalesB2b(orderedProductSalesB2B);
                            BeanUtil.copyProperties(trafficByAsinBean,tmp,copyOptions);
                            list.add(tmp);
                        }
                        // Process line by line.
                    }
                    tmpBusinessReportsBySkuService.saveBatch(list);
                } else {
                    //Handle content with binary data/other media types here.
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                log.error("SKU业务报表数据异常",e);
            } finally {
                if (closeThis != null) {
                    closeThis.close();
                }
            }
        }
    }

    public void getBusinessReportsByChild() throws Exception {
        DatainterfaceAuthority entityAuthority = datainterfaceAuthorityBaseService.getOne(Wrappers.<DatainterfaceAuthority>lambdaQuery().eq(DatainterfaceAuthority::getAppCode,"Amazon"), false);

        final List<ShopInfo> list = shopInfoService.list(Wrappers.lambdaQuery(ShopInfo.class)
                .eq(ShopInfo::getPlatform,"Amazon")
                .eq(ShopInfo::getSellerAuthStatus,"SQ01"));
        for(ShopInfo shop : list){

            List<String> marketplaceIds = Arrays.asList(shop.getMarketplaceId().split(","));

            CreateReportSpecification body = new CreateReportSpecification();
            body.setReportType("GET_SALES_AND_TRAFFIC_REPORT");
            body.setMarketplaceIds(marketplaceIds);
            ReportOptions reportOptions = new ReportOptions();
            reportOptions.put("dateGranularity","MONTH");
            reportOptions.put("asinGranularity","CHILD");

            body.setReportOptions(reportOptions);
//            body.setDataStartTime(AmzDateUtils.getOffsetDateTimeUTC(new Date()));
//            body.setDataEndTime(AmzDateUtils.getOffsetDateTimeUTC(new Date()));

            body.setDataStartTime(AmzDateUtils.getOffsetDateTimeUTC(DateUtil.offsetMonth(new Date(),-6)));
            body.setDataEndTime(AmzDateUtils.getOffsetDateTimeUTC(DateUtil.offsetMonth(new Date(),-6)));


            // 第一步 创建报告
            ReportsApi reportsApi = amazonUtil.getReportsApi(entityAuthority,shop,0.0167);
            final String reportId = createReport(reportsApi, body);
            // 第二步 检验报告是否完成
            ReportsApi reportsApi2 = amazonUtil.getReportsApi(entityAuthority,shop,2.0);
            final Report report = getReport(reportsApi2, reportId);
            // 第三步 获取报告连接
            ReportsApi reportsApi3 = amazonUtil.getReportsApi(entityAuthority,shop,0.0167);
            final ReportDocument reportDocument = reportsApi3.getReportDocument(report.getReportDocumentId());
            // 第四步 下载报告
            String compressionAlgorithm = null;
            if(null != reportDocument.getCompressionAlgorithm()){
                compressionAlgorithm = reportDocument.getCompressionAlgorithm().getValue();
            }
            System.out.println(reportDocument.getUrl());
            downloadByChild(reportDocument.getUrl(),compressionAlgorithm,shop);

        }
    }

    public void downloadByChild(String url, String compressionAlgorithm, ShopInfo shop) throws IOException, IllegalArgumentException {
        OkHttpClient httpclient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

        Response response = httpclient.newCall(request).execute();
        if (!response.isSuccessful()) {
            System.out.println(
                    String.format("Call to download content was unsuccessful with response code: %d and message: %s",
                            response.code(), response.message()));
            return;
        }

        try (ResponseBody responseBody = response.body()) {
            MediaType mediaType = MediaType.parse(response.header("Content-Type"));
            Charset charset = mediaType.charset();
            if (charset == null) {
                throw new IllegalArgumentException(String.format(
                        "Could not parse character set from '%s'", mediaType.toString()));
            }

            Closeable closeThis = null;
            try {
                InputStream inputStream = responseBody.byteStream();
                closeThis = inputStream;

                if ("GZIP".equals(compressionAlgorithm)) {
                    inputStream = new GZIPInputStream(inputStream);
                    closeThis = inputStream;
                }

                // This example assumes that the download content has a charset in the content-type header, e.g.
                // text/plain; charset=UTF-8
                if ("text".equals(mediaType.type()) && "plain".equals(mediaType.subtype())) {
                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream, charset);
                    closeThis = inputStreamReader;

                    BufferedReader reader = new BufferedReader(inputStreamReader);
                    closeThis = reader;

                    String line;
                    List<TmpBusinessReportsByChild> list = new ArrayList<>();
                    CopyOptions copyOptions = CopyOptions.create();
                    copyOptions.setOverride(false);
                    copyOptions.setIgnoreNullValue(true);
                    while ((line = reader.readLine()) != null) {
                        JSONObject json = GeneralUtil.getJsonObject(line);
                        JSONArray salesAndTrafficByAsin = json.getJSONArray("salesAndTrafficByAsin");
                        JSONObject reportSpecification = json.getJSONObject("reportSpecification");
                        Date dataTime = reportSpecification.getDate("dataStartTime");
                        for(int i = 0 ; i < salesAndTrafficByAsin.size() ; i++) {
                            TmpBusinessReportsByChild tmp = new TmpBusinessReportsByChild();
                            JSONObject itemJson = salesAndTrafficByAsin.getJSONObject(i);
                            String parentAsin = itemJson.getString("parentAsin");
                            String childAsin = itemJson.getString("childAsin");
                            String sku = itemJson.getString("sku");
                            JSONObject salesByAsin = itemJson.getJSONObject("salesByAsin");
                            JSONObject trafficByAsin = itemJson.getJSONObject("trafficByAsin");

                            Integer unitsOrdered = salesByAsin.getInteger("unitsOrdered");
                            Integer unitsOrderedB2B = salesByAsin.getInteger("unitsOrderedB2B");
                            Integer totalOrderItems = salesByAsin.getInteger("totalOrderItems");
                            Integer totalOrderItemsB2B = salesByAsin.getInteger("totalOrderItemsB2B");
                            JSONObject orderedProductSalesJson = salesByAsin.getJSONObject("orderedProductSales");
                            BigDecimal orderedProductSales = orderedProductSalesJson.getBigDecimal("amount");
                            String currency = orderedProductSalesJson.getString("currencyCode");
                            JSONObject orderedProductSalesB2BJson = salesByAsin.getJSONObject("orderedProductSalesB2B");
                            BigDecimal orderedProductSalesB2B = new BigDecimal("0");
                            if(orderedProductSalesB2BJson != null) {
                                orderedProductSalesB2B = orderedProductSalesB2BJson.getBigDecimal("amount");
                            }

                            TmpBusinessReportsByChild trafficByAsinBean = JSONObject.toJavaObject(trafficByAsin, TmpBusinessReportsByChild.class);
                            tmp.setCreateTime(new Date());
                            tmp.setLastUpdateTime(new Date());
                            tmp.setSid(shop.getId());
                            tmp.setCurrency(currency);
                            tmp.setChildAsin(childAsin);
                            tmp.setParentAsin(parentAsin);
                            tmp.setDataTime(dataTime);
                            tmp.setUnitsOrdered(unitsOrdered);
                            tmp.setUnitsOrderedB2b(unitsOrderedB2B);
                            tmp.setTotalOrderItems(totalOrderItems);
                            tmp.setTotalOrderItemsB2b(totalOrderItemsB2B);
                            tmp.setOrderedProductSales(orderedProductSales);
                            tmp.setOrderedProductSalesB2b(orderedProductSalesB2B);
                            BeanUtil.copyProperties(trafficByAsinBean,tmp,copyOptions);
                            list.add(tmp);
                        }
                        // Process line by line.
                    }
                    tmpBusinessReportsByChildService.saveBatch(list);
                } else {
                    //Handle content with binary data/other media types here.
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                log.error("子产品业务报表数据异常",e);
            } finally {
                if (closeThis != null) {
                    closeThis.close();
                }
            }
        }
    }

    public void getBusinessReportsByParent() throws Exception {
        DatainterfaceAuthority entityAuthority = datainterfaceAuthorityBaseService.getOne(Wrappers.<DatainterfaceAuthority>lambdaQuery().eq(DatainterfaceAuthority::getAppCode,"Amazon"), false);

        final List<ShopInfo> list = shopInfoService.list(Wrappers.lambdaQuery(ShopInfo.class)
                .eq(ShopInfo::getPlatform,"Amazon")
                .eq(ShopInfo::getSellerAuthStatus,"SQ01"));
        for(ShopInfo shop : list){

            List<String> marketplaceIds = Arrays.asList(shop.getMarketplaceId().split(","));

            CreateReportSpecification body = new CreateReportSpecification();
            body.setReportType("GET_SALES_AND_TRAFFIC_REPORT");
            body.setMarketplaceIds(marketplaceIds);
            ReportOptions reportOptions = new ReportOptions();
            reportOptions.put("dateGranularity","MONTH");
            reportOptions.put("asinGranularity","PARENT");

            body.setReportOptions(reportOptions);
//            body.setDataStartTime(AmzDateUtils.getOffsetDateTimeUTC(new Date()));
//            body.setDataEndTime(AmzDateUtils.getOffsetDateTimeUTC(new Date()));

            body.setDataStartTime(AmzDateUtils.getOffsetDateTimeUTC(DateUtil.offsetMonth(new Date(),-6)));
            body.setDataEndTime(AmzDateUtils.getOffsetDateTimeUTC(DateUtil.offsetMonth(new Date(),-6)));


            // 第一步 创建报告
            ReportsApi reportsApi = amazonUtil.getReportsApi(entityAuthority,shop,0.0167);
            final String reportId = createReport(reportsApi, body);
            // 第二步 检验报告是否完成
            ReportsApi reportsApi2 = amazonUtil.getReportsApi(entityAuthority,shop,2.0);
            final Report report = getReport(reportsApi2, reportId);
            // 第三步 获取报告连接
            ReportsApi reportsApi3 = amazonUtil.getReportsApi(entityAuthority,shop,0.0167);
            final ReportDocument reportDocument = reportsApi3.getReportDocument(report.getReportDocumentId());
            // 第四步 下载报告
            String compressionAlgorithm = null;
            if(null != reportDocument.getCompressionAlgorithm()){
                compressionAlgorithm = reportDocument.getCompressionAlgorithm().getValue();
            }
            System.out.println(reportDocument.getUrl());
            downloadByParent(reportDocument.getUrl(),compressionAlgorithm,shop);

        }
    }

    public void downloadByParent(String url, String compressionAlgorithm, ShopInfo shop) throws IOException, IllegalArgumentException {
        OkHttpClient httpclient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

        Response response = httpclient.newCall(request).execute();
        if (!response.isSuccessful()) {
            System.out.println(
                    String.format("Call to download content was unsuccessful with response code: %d and message: %s",
                            response.code(), response.message()));
            return;
        }

        try (ResponseBody responseBody = response.body()) {
            MediaType mediaType = MediaType.parse(response.header("Content-Type"));
            Charset charset = mediaType.charset();
            if (charset == null) {
                throw new IllegalArgumentException(String.format(
                        "Could not parse character set from '%s'", mediaType.toString()));
            }

            Closeable closeThis = null;
            try {
                InputStream inputStream = responseBody.byteStream();
                closeThis = inputStream;

                if ("GZIP".equals(compressionAlgorithm)) {
                    inputStream = new GZIPInputStream(inputStream);
                    closeThis = inputStream;
                }

                // This example assumes that the download content has a charset in the content-type header, e.g.
                // text/plain; charset=UTF-8
                if ("text".equals(mediaType.type()) && "plain".equals(mediaType.subtype())) {
                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream, charset);
                    closeThis = inputStreamReader;

                    BufferedReader reader = new BufferedReader(inputStreamReader);
                    closeThis = reader;

                    String line;
                    List<TmpBusinessReportsByParent> list = new ArrayList<>();
                    CopyOptions copyOptions = CopyOptions.create();
                    copyOptions.setOverride(false);
                    copyOptions.setIgnoreNullValue(true);
                    while ((line = reader.readLine()) != null) {
                        JSONObject json = GeneralUtil.getJsonObject(line);
                        JSONArray salesAndTrafficByAsin = json.getJSONArray("salesAndTrafficByAsin");
                        JSONObject reportSpecification = json.getJSONObject("reportSpecification");
                        Date dataTime = reportSpecification.getDate("dataStartTime");
                        for(int i = 0 ; i < salesAndTrafficByAsin.size() ; i++) {
                            TmpBusinessReportsByParent tmp = new TmpBusinessReportsByParent();
                            JSONObject itemJson = salesAndTrafficByAsin.getJSONObject(i);
                            String parentAsin = itemJson.getString("parentAsin");
                            String childAsin = itemJson.getString("childAsin");
                            String sku = itemJson.getString("sku");
                            JSONObject salesByAsin = itemJson.getJSONObject("salesByAsin");
                            JSONObject trafficByAsin = itemJson.getJSONObject("trafficByAsin");

                            Integer unitsOrdered = salesByAsin.getInteger("unitsOrdered");
                            Integer unitsOrderedB2B = salesByAsin.getInteger("unitsOrderedB2B");
                            Integer totalOrderItems = salesByAsin.getInteger("totalOrderItems");
                            Integer totalOrderItemsB2B = salesByAsin.getInteger("totalOrderItemsB2B");
                            JSONObject orderedProductSalesJson = salesByAsin.getJSONObject("orderedProductSales");
                            BigDecimal orderedProductSales = orderedProductSalesJson.getBigDecimal("amount");
                            String currency = orderedProductSalesJson.getString("currencyCode");
                            JSONObject orderedProductSalesB2BJson = salesByAsin.getJSONObject("orderedProductSalesB2B");
                            BigDecimal orderedProductSalesB2B = new BigDecimal("0");
                            if(orderedProductSalesB2BJson != null) {
                                orderedProductSalesB2B = orderedProductSalesB2BJson.getBigDecimal("amount");
                            }

                            TmpBusinessReportsByParent trafficByAsinBean = JSONObject.toJavaObject(trafficByAsin, TmpBusinessReportsByParent.class);
                            tmp.setCreateTime(new Date());
                            tmp.setLastUpdateTime(new Date());
                            tmp.setSid(shop.getId());
                            tmp.setCurrency(currency);
                            tmp.setParentAsin(parentAsin);
                            tmp.setDataTime(dataTime);
                            tmp.setUnitsOrdered(unitsOrdered);
                            tmp.setUnitsOrderedB2b(unitsOrderedB2B);
                            tmp.setTotalOrderItems(totalOrderItems);
                            tmp.setTotalOrderItemsB2b(totalOrderItemsB2B);
                            tmp.setOrderedProductSales(orderedProductSales);
                            tmp.setOrderedProductSalesB2b(orderedProductSalesB2B);
                            BeanUtil.copyProperties(trafficByAsinBean,tmp,copyOptions);
                            list.add(tmp);
                        }
                        // Process line by line.
                    }
                    tmpBusinessReportsByParentService.saveBatch(list);
                } else {
                    //Handle content with binary data/other media types here.
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                log.error("父产品业务报表数据异常",e);
            } finally {
                if (closeThis != null) {
                    closeThis.close();
                }
            }
        }
    }
}
